<template>
  <div class="app-container">
    <div v-show="!desigenerInfo.visible">
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clearType="clearType"
        />
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList" />
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :check-box="false"
        :tab-index="true"
        :highlight-row="false"
        :handle="tableInfo.handle"
      >
        <template v-slot:col-width="scope">
          {{ scope.row.width || 0 }} * {{ scope.row.height || 0 }}
        </template>
        <template v-slot:col-pageWidth="scope">
          {{ scope.row.pageWidth || 0 }}mm * {{ scope.row.pageHeight || 0 }}mm
        </template>
        <template v-slot:col-horizontally="scope">
          {{
            scope.row.horizontally === 1
              ? '纵向打印'
              : scope.row.horizontally === 2
              ? '横向打印'
              : '-'
          }}
        </template>
      </table-container>
    </div>
    <desigener
      v-if="desigenerInfo.visible"
      v-model:visible="desigenerInfo.visible"
      :title="desigenerInfo.title"
      :formData="formInfo.data"
      :desigenerType="desigenerInfo.desigenerType"
      @callback="desigenerCallback"
    ></desigener>
    <page-dialog
      v-if="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="formInfo.ref"
        :data="formInfo.data"
        :field-list="formInfo.fieldList"
        :rules="formInfo.rules"
        :label-width="formInfo.labelWidth"
      >
        <template v-slot:form-customizeTableSettingId>
          <el-select
            v-model="formInfo.data.customizeTableSettingId"
            clearable
            filterable
            @visible-change="visibleChange"
            :filterMethod="filterMethod"
            placeholder="请选择关联表格"
          >
            <el-option
              v-for="(item, index) in formInfo.options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </template>
        <template v-slot:form-horizontally>
          <el-select
            v-model="formInfo.data.horizontally"
            placeholder="请选择打印方向"
          >
            <el-option
              v-for="(item, index) in printType"
              :key="index"
              :label="item.name"
              :value="item.code"
            >
            </el-option>
          </el-select>
        </template>
      </page-form>
    </page-dialog>
  </div>
</template>

<script setup name="printConfig">
import TableContainer from '@/components/TableContainer/index'

import PageDialog from '@/components/PageDialog/index'
import PageForm from '@/components/PageForm/index'
import Desigener from './desigener'
import {
  fatchPrintTemplate,
  postPrintTemplate,
  putPrintTemplate,
  deletePrintTemplate,
} from '@/api/base'
import { getCustomizeAll } from '@/api/customize'
import pinyin from 'js-pinyin'
const { proxy } = getCurrentInstance()

const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: fatchPrintTemplate,
  fieldList: [
    { label: '名称', value: 'name' },
    { label: '关联自定义表格', value: 'customizeTableSettingName' },
    { label: '模板宽高', value: 'width', type: 'slot' },
    { label: '纸张大小', value: 'pageWidth', type: 'slot' },
    { label: '打印方向', value: 'horizontally', type: 'slot' },
    { label: '创建人', value: 'createUserName' },
    { label: '备注', value: 'remark' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '设计',
        event: printDesign,
        show: true,
      },
      {
        label: '预览',
        event: previewTemp,
        show: true,
      },
      {
        label: '复制',
        event: copyTemp,
        show: true,
      },
      {
        label: '删除',
        event: remove,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
    ],
  },
})
const filterInfo = reactive({
  query: {
    nameLike: '',
    sort: 'create_time desc',
  },
  searchList: [
    {
      componentType: 'input',
      label: '模板名称',
      value: 'nameLike',
      event: search,
    },
  ],
  searchBtn: [{ type: 'button', label: '搜索', event: search }],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
    },
  ],
})
const formInfo = reactive({
  ref: null,
  options: [],
  copyOptions: [],
  data: {
    name: '232',
    customizeTableSettingId: '',
    width: 750,
    height: 500,
    pageWidth: 750,
    pageHeight: 500,
    remark: '',
    horizontally: 1, //打印模式：1竖打，2横打
  },
  fieldList: [
    {
      label: '模板名称',
      value: 'name',
      type: 'input',
    },
    {
      label: '关联表格',
      value: 'customizeTableSettingId',
      type: 'slot',
    },
    {
      label: '模板宽度',
      value: 'width',
      type: 'number',
    },
    {
      label: '模板高度',
      value: 'height',
      type: 'number',
    },
    {
      label: '纸张宽度',
      value: 'pageWidth',
      type: 'number',
    },
    {
      label: '纸张高度',
      value: 'pageHeight',
      type: 'number',
    },
    {
      label: '打印方向',
      value: 'horizontally',
      type: 'slot',
      labelTip: '1纵向打印，2横向打印',
      min: 1,
      max: 2,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
    width: [
      { required: true, validator: proxy.$validate.positive, trigger: 'blur' },
    ],
    height: [
      { required: true, validator: proxy.$validate.positive, trigger: 'blur' },
    ],
    pageWidth: [
      { required: true, validator: proxy.$validate.positive, trigger: 'blur' },
    ],
    pageHeight: [
      { required: true, validator: proxy.$validate.positive, trigger: 'blur' },
    ],
    horizontally: [
      { required: true, message: '请输入打印模式', trigger: 'blur' },
    ],
  },
  labelWidth: '120px',
})
const dialogInfo = reactive({
  title: '',
  visible: false,
  width: '40%',
  btLoading: false,
  btList: [
    { label: '关闭', type: '', icon: '', event: close, show: true },
    {
      label: '保存',
      type: 'primary',
      icon: '',
      event: save,
      saveLoading: false,
      show: true,
    },
  ],
})
const desigenerInfo = reactive({
  visible: false,
  title: '打印模板设计',
  desigenerType: '',
})
const clearType = ref(true)

const printType = computed(() => {
  let option = proxy.$store.state.permission.dict['print-type'] || []

  if (option.length) {
    option.forEach((item) => {
      item.code = Number(item.code)
    })
  }
  return option
})
function visibleChange(val) {
  //下拉框出现/隐藏时触发
  if (!val) {
    formInfo.options = formInfo.copyOptions
  }
}
function filterMethod(value) {
  //	自定义搜索方法
  if (value) {
    let result = []
    formInfo.copyOptions.forEach((item) => {
      pinyin.setOptions({ checkPolyphone: false, charCase: 1 })
      const resultEng = pinyin.getCamelChars(item.name).toUpperCase()
      const matchResult = item.name.indexOf(value) !== -1 || resultEng.indexOf(value.toUpperCase()) !== -1
      // let matchResult = PinYinMatch.match(item.name, value)
      if (matchResult) {
        result.push(item)
      }
    })
    formInfo.options = result
  } else {
    formInfo.options = formInfo.copyOptions
  }
}

function getList() {
  tableInfo.refresh = Math.random()
}
function search() {
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}
function printDesign(row) {
  formInfo.data = row
  desigenerInfo.visible = true
}
function create() {
  dialogInfo.title = '新增模板'
  getTableKey()
  close()
  dialogInfo.visible = true
}
function copyTemp(row) {
  formInfo.data = {
    name: row.name,
    customizeTableSettingId: row.customizeTableSettingId,
    defaultCustomizeTableSettingId: row.customizeTableSettingId,
    width: row.width,
    height: row.height,
    pageWidth: row.pageWidth,
    pageHeight: row.pageHeight,
    horizontally: row.horizontally,
    remark: '',
    templateContent: row.templateContent,
    templateColumnContent: row.templateColumnContent,
  }
  desigenerInfo.desigenerType = 'copy'
  getTableKey()
  dialogInfo.visible = true
}
function previewTemp(row) {
  let page = proxy.$fn.deepClone(row)
  let params = {
    title: page.name,
    width: page.width,
    height: page.height,
    pageWidth: page.pageWidth,
    pageHeight: page.pageHeight,
    horizontally: page.horizontally,
    tempItems: JSON.parse(page.templateContent),
  }
  proxy.$lodop.previewTemp(params)
}
function close() {
  dialogInfo.visible = false
  formInfo.data = {
    name: '',
    customizeTableSettingId: '',
    width: 0,
    height: 0,
    pageWidth: 0,
    pageHeight: 0,
    horizontally: 1,
    remark: '',
  }
  desigenerInfo.desigenerType = ''
}
function getTableKey() {
  getCustomizeAll().then((res) => {
    if (res && res.success) {
      formInfo.options = res.data
      formInfo.copyOptions = proxy.$fn.deepClone(formInfo.options)
    }
  })
}
function desigenerCallback(obj, callback) {
  let api = obj.id ? putPrintTemplate : postPrintTemplate
  api(obj).then((res) => {
    if (res && res.success) {
      search()
      callback()
      desigenerInfo.desigenerType = ''
    }
  })
}
function save() {
  formInfo.ref.validate((valid) => {
    if (valid) {
      dialogInfo.visible = false
      proxy.$nextTick(() => {
        desigenerInfo.visible = true
      })
    }
  })
}
function remove(row) {
  deletePrintTemplate([row.id]).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
</script>

<style scoped lang="scss">
// .left-container {
//   min-width: 400px;
//   max-width: 400px;
//   .main-flex {
//     padding: 0 20px;
//     box-sizing: border-box;
//   }
// }
// .right-container {
//   width: calc(100%-400px);
// }
</style>
